import timLogin from '@/utils/timLogin.js' // 导入tim 登录
let timer = null
export default {
  data() {
    return {
      navigationTitle: '聊天', // 导航栏标题
      formData: {
        content: '',
        limit: 15,
        index: 1
      },
      messageList: [],
      loading: true, //标识是否正在获取数据
      mpInputMargin: false, //适配微信小程序 底部输入框高度被顶起的问题
      chatType: 'voice',  // 图标类型 'voice'语音 'keyboard'键盘
      voiceTitle: '按住 说话',
      Recorder: uni.getRecorderManager(),
      Audio: uni.createInnerAudioContext(),
      recording: false, //标识是否正在录音
      isStopVoice: false, //加锁 防止点击过快引起的当录音正在准备(还没有开始录音)的时候,却调用了stop方法但并不能阻止录音的问题
      voiceInterval: null,
      voiceTime: 0, //总共录音时长
      canSend: true, //是否可以发送
      PointY: 0, //坐标位置
      voiceIconText: '正在录音...',
      showFunBtn: false, //是否展示功能型按钮
      AudioExam: null, //正在播放音频的实例
      hideEmoji: true, // 是否显示emoji
      emojiList: this.$commen.emojiList, // 表情列表
      showFunBtn: false,
      scrollAnimation: false,
      scrollTop: 0,
      scrollToView: '',
      conversationID: '', // 消息接收方ID
      isHistoryLoading: false, // 是否正在加载历史
      nextReqMessageID: '', // 用于续拉，分页续拉时需传入该字段。
      isCompleted: false ,// 表示是否已经拉完所有消息。
      selectionEnd: -1,
      imType: 'C2C' ,// 聊天类型 (C2C:单聊,GROUP:群聊,MASS:群发)
      pageOnloadSuccess: false,
      videoLink: '', // 视频地址
      videoContext: null,
      userGroupInfo: null, // 用户群信息
      keyboardHeight: 0, // 键盘高度
      windowHeight: uni.getSystemInfoSync().windowHeight, // 页面高度
      autoFocus: false // 自动聚焦
    }
  },
  computed: {
    timUserInfo() {
      return this.$store.state.timUserInfo
    },
    massTempData() {
      return this.$store.state.massTempData
    },
    pageHeight() {
      return (this.windowHeight - this.keyboardHeight) + 'px'
    }
  },
  onLoad(option) {
    this.windowHeight = uni.getSystemInfoSync().windowHeight
    this.conversationID = option.userid || option.id
    this.imType = option.type || 'C2C'

    if(option.name) {
      // this.navigationTitle = decodeURIComponent(option.name)
      uni.setNavigationBarTitle({
        title: decodeURIComponent(option.name)
      })
    }

    //录音开始事件
    this.Recorder.onStart(e => {
      this.beginVoice()
    })
    //录音结束事件
    this.Recorder.onStop(res => {
      clearInterval(this.voiceInterval)
      this.handleRecorder(res)
    })
    //音频停止事件
    this.Audio.onStop(e => {
      this.closeAnmition()
    })
    //音频播放结束事件
    this.Audio.onEnded(e => {
      this.closeAnmition()
    })
    // 登录tim
    if(this.imType !== 'MASS') {
      uni.showNavigationBarLoading()
    } else {
      uni.hideLoading()
      this.autoFocus = true
      uni.setNavigationBarTitle({
        title: '群发助手'
      })
    }
    if(this.$store.state.isSDKReady) {
      if(this.imType !== 'MASS'){
        this.onReadyStateUpdate()
      }
    } else {
      timLogin(() => {
        if(this.imType !== 'MASS'){
          this.onReadyStateUpdate()
        }
      })
    }

    // 监听消息接收
    if(this.imType !== 'MASS'){
      this.tim.on(this.$TIM.EVENT.MESSAGE_RECEIVED, this.messageReceived)
    }

    this.videoContext = uni.createVideoContext('video')

    // #ifdef APP-PLUS
    uni.onKeyboardHeightChange(res => {
      this.keyboardHeight = res.height
    })
    // #endif
  },
  onShow() {
    if(this.imType !== 'MASS'){
      this.tim.setMessageRead({
        conversationID: this.imType + this.conversationID
      }).then(function(imResponse) {
      }).catch(function(imError) {
      })

      if(this.imType === 'GROUP') {
        this.getGroupInfo()
      }
    } else {
      uni.hideLoading()
    }

    this.$nextTick(() => {
      setTimeout(() => {
        this.pageOnloadSuccess = true
      }, 500)
    })
  },
  watch: {
    userGroupInfo: {
      deep: true,
      handler (newVal, oldVal) {
        // #ifdef APP-PLUS
        let webview = this.$mp.page.$getAppWebview()
        if (newVal && this.timUserInfo.isService) {
          webview.setTitleNViewButtonStyle(1, {
            text: '\ue64b',
            width: '30px'
          })
        } else {
          webview.setTitleNViewButtonStyle(1, {
            text: '',
            width: 0
          })
        }
        // #endif
        // #ifdef H5
        let view = document.querySelectorAll('.uni-page-head-ft .uni-page-head-btn')
        if (newVal && this.timUserInfo.isService) {
          view[1].childNodes[0].innerHTML = '\ue64b'
          view[1].style.width = '30px'
        } else {
          view[1].childNodes[0].innerHTML = ''
          view[1].style.width = '0'
        }
        // #endif
      }
    }
  },
  methods: {
    isJSON(str) {
      if (typeof str === 'string') {
        try {
          let obj = JSON.parse(str)
          return obj
        } catch(e) {
          return false
        }
      }
    },
    //触发滑动到顶部(加载历史信息记录)
    loadHistory(e){
      if(this.isCompleted) return false
      this.isHistoryLoading = true
      // 更多消息列表
      let conversationID = this.imType + this.conversationID
      let promise = this.tim.getMessageList({
        conversationID: conversationID,
        nextReqMessageID: this.nextReqMessageID,
        count: 20,
      })
      promise.then(res => {
        let list = res.data.messageList.map(data => {
          data.anmitionPlay = false
          return data
        })
        this.messageList = list.concat(this.messageList)
        this.nextReqMessageID =  res.data.nextReqMessageID // 用于续拉，分页续拉时需传入该字段。
        this.isCompleted =  res.data.isCompleted
        this.isHistoryLoading = false

        if(list.length > 0) {
          // 这段代码很重要，不然每次加载历史数据都会跳到顶部
          this.$nextTick(function() {
            this.scrollToView = list[list.length - 1].ID
            this.$nextTick(function() {
              this.scrollAnimation = true
            })
          })
          if(this.imType === 'GROUP') {
            this.getMemberInfo()
          }
        }
      })

    },
    onReadyStateUpdate(data) {
      let promise = this.tim.getMessageList({
        conversationID: this.imType + this.conversationID,
        count: 20,
      })
      promise.then(res => {
        const list = res.data.messageList.map(data => {
          data.anmitionPlay = false
          return data
        }) // 消息列表。
        this.nextReqMessageID = res.data.nextReqMessageID // 用于续拉，分页续拉时需传入该字段。
        this.isCompleted = res.data.isCompleted // 表示是否已经拉完所有消息。

        this.messageList = list

        if(list.length > 0) {
          this.$nextTick(() => {
            this.scrollToView = list[list.length - 1].ID
          })
          if(this.imType === 'GROUP') {
            this.getMemberInfo()
          }
        }
        uni.hideNavigationBarLoading()
      }).catch(imError => {
        uni.hideNavigationBarLoading()
      })

      // 如果当前是单聊状态并且自己是服务商身份，就获取对方群信息
      if(this.imType === 'C2C') {
        this.getUserGroupInfo()
      }
    },
    // 监听消息
    messageReceived(event) {
      let message = this.messageList
      event.data.map(data => {
        if(data.conversationID === this.imType + this.conversationID){
          data.anmitionPlay = false
          message.push(data)
        }
      })

      this.messageList = message
      this.$nextTick(() => {
        this.scrollToView = this.messageList[this.messageList.length - 1].ID
      })
    },
    //切换语音或者键盘方式
    switchChatType() {
      this.chatType = this.chatType === 'voice' ? 'keyboard' : 'voice'
      if(this.chatType === 'voice') {
        uni.hideKeyboard()
      }
      this.showFunBtn = false
      this.hideEmoji = true
    },
    //准备开始录音
    startVoice(e) {
      if(!this.Audio.paused){
        //如果音频正在播放 先暂停。
        this.stopAudio(this.AudioExam)
      }
      this.recording = true
      this.isStopVoice = false
      this.canSend = true
      this.voiceIconText = '正在录音...'
      this.PointY = e.touches[0].clientY
      this.Recorder.start({
        format: 'mp3'
      })
    },
    //录音已经开始
    beginVoice(){
      if (this.isStopVoice) {
        this.Recorder.stop()
        return
      }
      this.voiceTitle = '松开结束'
      this.voiceInterval =  setInterval(() => {
        this.voiceTime ++
      },1000)
    },
    //move 正在录音中
    moveVoice(e){
      const PointY = e.touches[0].clientY
      const slideY = this.PointY - PointY
      if(slideY > uni.upx2px(120)){
        this.canSend = false
        this.voiceIconText = '松开手指取消发送 '
      }else if(slideY > uni.upx2px(60)){
        this.canSend = true
        this.voiceIconText = '手指上滑取消发送 '
      }else{
        this.voiceIconText = '正在录音...'
      }
    },
    //结束录音
    endVoice() {
      this.isStopVoice = true //加锁 确保已经结束录音并不会录制
      this.Recorder.stop()
      this.voiceTitle = '按住说话'
    },
    //录音被打断
    cancelVoice(e){
      this.voiceTime = 0
      this.voiceTitle = '按住说话'
      this.canSend = false
      this.Recorder.stop()
    },
    //处理录音文件
    async handleRecorder({ tempFilePath,duration }) {
      let contentDuration
      // #ifdef MP-WEIXIN
      this.voiceTime = 0
      if (duration < 600) {
        this.voiceIconText = '说话时间过短'
        setTimeout(() => {
          this.recording = false
        },200)
        return
      }
      contentDuration = duration/1000
      // #endif

      // #ifdef APP-PLUS
      contentDuration = this.voiceTime +1
      this.voiceTime = 0
      if(contentDuration <= 0) {
        this.voiceIconText = '说话时间过短'
        setTimeout(() => {
          this.recording = false
        },200)
        return
      };
      // #endif

      this.recording = false
      const params = {
        contentType: 2,
        content: tempFilePath,
        contentDuration: Math.ceil(contentDuration)
      }
      uni.showLoading({
        title: '加载中'
      })
      try{
        let file = await this.$api.files.uploadFile({
          filePath: tempFilePath
        }, 'mp3')
        this.canSend && this.sendFileMsg(`${file.baseUrl + file.url}`, {
          type: 'mp3',
          contentDuration: Math.ceil(contentDuration)
        })
        uni.hideLoading()
      }catch(e){
        uni.hideLoading()
      }
    },
    //控制播放还是暂停音频文件
    handleAudio(item) {
      this.AudioExam = item
      this.Audio.paused ? this.playAudio(item) : this.stopAudio(item)
    },
    //播放音频
    playAudio(item) {
      this.Audio.src = item.payload.description
      this.Audio.hasBeenSentId = item.from
      this.Audio.play()
      console.log('开始播放')
      item.anmitionPlay = true
    },
    //停止音频
    stopAudio(item) {
      item.anmitionPlay = false
      this.Audio.src = ''
      this.Audio.stop()
    },
    //关闭动画
    closeAnmition() {
      const hasBeenSentId = this.Audio.hasBeenSentId
      const item = this.messageList.find(it => it.from === hasBeenSentId)
      item.anmitionPlay = false
    },
    //发送文字消息
    sendTextMsg(data) {
      let self = this
      let arr = []
      if(self.imType === 'MASS') {
        arr = self.$store.state.massTempData
      } else {
        arr.push({
          id: self.conversationID,
          type: self.imType
        })
      }
      for(let i in arr){
        let message = this.tim.createTextMessage({
          to: arr[i].id,
          conversationType: arr[i].type,
          payload: {
            text: self.formData.content
          }
        })
        this.sendMessage(message, Number(i) === 0)
      }
    },
    // 发送文件消息
    sendFileMsg(url, type) {
      let self = this
      let arr = []

      if(self.imType === 'MASS') {
        arr = self.$store.state.massTempData
      } else {
        arr.push({
          id: self.conversationID,
          type: self.imType
        })
      }
      for(let i in arr){
        let message = this.tim.createCustomMessage({
          to: arr[i].id,
          conversationType: arr[i].type,
          payload: {
            data: 'chatFile',
            description: url,
            extension: JSON.stringify(type)
          }
        })
        this.sendMessage(message, Number(i) === 0)
      }
    },
    // 发送消息
    sendMessage(message, first) {
      let pomise = this.tim.sendMessage(message)
      pomise.then(res => {
        console.log(res)
      }).catch(err => {
        console.log(err)
      })
      if(first && this.imType === 'MASS') {
        this.AddGroupSendMessage(message)
        uni.navigateBack({
          delta: 1
        })
        return false
      }
      if(first || this.imType !== 'MASS') {
        this.messageList.push(message)
        this.$nextTick(() => {
          this.formData.content = ''
          this.hideEmoji = true
          if(this.showFunBtn){
            this.showFunBtn = false
          }
          //h5浏览器并没有很好的办法控制键盘一直处于唤起状态 而且会有样式性的问题
          // #ifdef H5
          uni.hideKeyboard()
          // #endif

          this.scrollToView = message.ID
        })
      }
    },
    // 点击列表区域隐藏抽屉
    hideDrawer(){
      this.hideEmoji = true
      this.showFunBtn = false
    },
    // 显示隐藏emoji
    switchEmoji() {
      this.hideEmoji = !this.hideEmoji
      console.log(this.hideEmoji)
      this.showFunBtn = false
    },
    // 显示隐藏更多操作
    switchFun() {
      this.showFunBtn = !this.showFunBtn
      this.hideEmoji = true
    },
    //选择图片
    chooseImage(sourceType){
      uni.chooseImage({
        sourceType,
        sizeType: ['compressed'],
        count: 1,
        success: async res => {
          uni.showLoading({
            title: '加载中'
          })
          try{
            let file = await this.$api.files.uploadImg({
              filePath: res.tempFilePaths[0]
            })
            this.sendFileMsg(`${file.baseUrl + file.url}`, {
              type: 'img'
            })
            uni.hideLoading()
          }catch(e){
            //TODO handle the exception
            uni.hideLoading()
          }
        }
      })
    },
    //添加表情
    addEmoji(em) {
      this.formData.content += em.alt
    },
    //替换表情符号为图片
    replaceEmoji(str) {
      let replacedStr = str.replace(/\[([^(\]|\[)]*)\]/g, (item, index) => {
        for (let i = 0; i < this.emojiList.length; i++) {
          let row = this.emojiList[i]
          for (let j = 0; j < row.length; j++) {
            let EM = row[j]
            if (EM.alt === item) {
              //在线表情路径，图文混排必须使用网络路径，请上传一份表情到你的服务器后再替换此路径
              //比如你上传服务器后，你的100.gif路径为https://www.xxx.com/emoji/100.gif 则替换onlinePath填写为https://www.xxx.com/emoji/
              let onlinePath = EM.url.indexOf('files.yzsheng.com') > -1 ? '' : 'https://files.yzsheng.com/client/emoji/'
              let imgstr = '<img src="' + onlinePath + EM.url + '" style="vertical-align: middle;">'
              return imgstr
            }
          }
        }
      })
      return replacedStr
    },
    //聊天的节点加上外层的div
    nodesFliter(str) {
      let nodeStr = '<div style="align-items: center;word-wrap:break-word;">' + this.replaceEmoji(str) + '</div>'
      return nodeStr
    },

    // 点击群聊
    onClickGroup() {
      let name = this.userGroupInfo.group_name ? '&name=' + encodeURIComponent(this.userGroupInfo.group_name) : ''
      if(this.showFunBtn){
        this.showFunBtn = false
      }
      uni.navigateTo({
        url: `/pages_chat/chat/chat?id=${this.userGroupInfo.id}&type=GROUP${name}`
      })
    },
    // 点击右上角查看跟多
    onClickMore(){
      if(this.imType === 'C2C'){
        uni.navigateTo({
          url: '/pages_userModule/memberDetails/memberDetails?from=chat&id=' + this.conversationID
        })
      } else if(this.imType === 'GROUP') {
        uni.navigateTo({
          url: '/pages_chat/group/setting/setting?id=' + this.conversationID
        })
      }
    },
    // 拍摄视频
    chooseVideo() {
      uni.chooseVideo({
        count: 1,
        sourceType: ['camera', 'album'],
        success: async res => {
          uni.showLoading({
            title: '加载中'
          })
          try{
            console.log(res)
            let file = await this.$api.files.uploadFile({
              filePath: res.tempFilePath
            }, 'mp4')
            this.sendFileMsg(`${file.baseUrl + file.url}`, {
              type: 'mp4'
            })
            uni.hideLoading()
          }catch(e){
            //TODO handle the exception
            uni.hideLoading()
          }
        }
      })
    },
    // 点击图片查看大图
    onClickImg(item) {
      uni.previewImage({
        urls: [item],
        current: 0
      })
    },
    // 点击播放视频
    onPlayVideo(url) {
      if(url) {
        this.videoLink = url
        this.videoContext.requestFullScreen()
        setTimeout(() => {
          this.videoContext.seek(0)
          this.videoContext.play()
        }, 500)
      }
    },
    // 视频退出全屏
    onFullscreenchange(data) {
      console.log(data.detail.fullScreen)
      if(!data.detail.fullScreen) {
        this.videoContext.stop()
        this.videoLink = ''
      }
    },
    // 跳转用户详情
    onJumpMemnerDetails(data) {
      uni.navigateTo({
        url: `/pages_userModule/memberDetails/memberDetails?id=${data.from}&from=chat`
      })
    },
    // 群发记录提交
    AddGroupSendMessage(data) {
      let users = this.$store.state.massTempData.map(item => {
        return {
          user_id: item.id,
          type: item.type === 'GROUP' ? 1 : 0
        }
      })

      let message = ''
      if(data.payload.text) {
        message = data.payload.text
      }else if(this.isJSON(data.payload.extension) && this.isJSON(data.payload.extension).type === 'mp3') {
        message = '[语音消息]'
      }else if(this.isJSON(data.payload.extension) && this.isJSON(data.payload.extension).type === 'img') {
        message = '[图片]'
      }else if(this.isJSON(data.payload.extension) && this.isJSON(data.payload.extension).type === 'mp4') {
        message = '[视频]'
      }

      try{
        let res = this.$api.chat.AddGroupSendMessage({
          message: message,
          sendMessageUserRelations: users
        })
      }catch(e){
        //TODO handle the exception
      }
    },
    // 获取用户群信息
    async getUserGroupInfo() {
      try{
        let res = await this.$api.chat.GetMyIMGroup({
          userId: this.conversationID
        })
        this.userGroupInfo = res.data
      }catch(e){
        //TODO handle the exception
      }
    },
    // 获取用户信息
    getMemberInfo() {
      this.messageList.map((item, index) => {
        if(item.type === 'TIMGroupTipElem' && item.conversationType === 'GROUP' && item.payload.operationType === 1) {
          this.tim.getUserProfile({
            userIDList: item.payload.userIDList
          }).then(data => {
            item.payload.nick = data.data[0].nick
            this.$set(this.messageList, index, item)
          }).catch(err => {
            item.payload.nick = '未知'
          })
        }
      })
    },
    // 点击分享链接
    onClickShareLink(data) {
      data = this.isJSON(data)
      if(data) {
        if(data.href.indexOf('/pages') > -1) {
          let href = data.href.split('/pages')[1]
          uni.navigateTo({
            url: `/pages${href}`
          })
        } else if(data.href.indexOf('/7maiche/#/') > -1) {
          let href = data.href.split('/7maiche/#/')[1]
          uni.navigateTo({
            url: `/${href}`
          })
        } else if(data.href.indexOf('ztch5.yzsheng.com/#/') > -1) {
          let href = data.href.split('ztch5.yzsheng.com/#/')[1]
          uni.navigateTo({
            url: `/${href}`
          })
        } else {
          uni.navigateTo({
            url: `/pages_common/webview/webview?url=${encodeURIComponent(data.href)}`
          })
        }
      }
    },
    // input获取焦点
    inputFocus(e) {
      // #ifdef APP-PLUS
      this.keyboardHeight = e.detail.height
      // #endif
      this.hideDrawer()
      this.scrollToView = 'footer'
    },
    // input失去焦点
    inputBlur() {
      // #ifdef APP-PLUS
      this.keyboardHeight = 0
      if(plus.os.name === 'Android') {
        clearInterval(timer)
      }
      // #endif
    },
    // 点击拨打电话
    onClickCallPhone() {
      uni.makePhoneCall({
        phoneNumber: `${this.userGroupInfo.mobile}`
      })
    },
    // 获取群信息
    getGroupInfo(){
      this.tim.getConversationProfile(`GROUP${this.conversationID}`).then(imResponse => {
        let res = imResponse.data.conversation
        if(res && res.groupProfile && res.groupProfile.name) {
          uni.setNavigationBarTitle({
            title: res.groupProfile.name
          })
        }
      }).catch(imError => {
      })
    }
  },
  onUnload() {
    this.tim.off(this.$TIM.EVENT.MESSAGE_RECEIVED, this.messageReceived)
  },
  onNavigationBarButtonTap(e) {
    if(e.id === 'more') {
      this.onClickMore()
    } else if(e.id === 'group'){
      if(this.userGroupInfo) {
        this.onClickGroup()
      }
    }
  }
}
